package org.android.brasil.projetos.oktoberfest2011.view.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.Handler;
import android.util.Log;

public class HTTPThread extends Thread {

	public static final int STATUS_PENDING = 0;
	public static final int STATUS_RUNNING = 1;
	public static final int STATUS_FINISHED = 2;

	private boolean error = false;
	private Exception exception = null;
	private String url;
	private String local;
	private int status = STATUS_PENDING;
	private SoftReference<Handler> handler;

	public HTTPThread(String url, String local, Handler handler) {
		this.url = url;
		this.local = local;
		this.handler = new SoftReference<Handler>(handler);
	}

	@Override
	public void start() {
		if (this.getStatus() == STATUS_PENDING) {
			synchronized (this) {
				this.status = STATUS_RUNNING;
			}
			super.start();
		}
	}

	public void run() {
		try {
			URL request = new URL(this.url);
			InputStream is = (InputStream) request.getContent();
			FileOutputStream fos = new FileOutputStream(this.local);
			try {
				byte[] buffer = new byte[4096];
				int l;
				while ((l = is.read(buffer)) != -1) {
					fos.write(buffer, 0, l);
				}
			} catch (IOException e) {
				Log.e(this.getClass().getSimpleName(), e.getMessage(), e);
			} finally {
				is.close();
				fos.flush();
				fos.close();
			}
		} catch (MalformedURLException e) {
			Log.e(this.getClass().getSimpleName(), e.getMessage(), e);
		} catch (IOException e) {
			Log.e(this.getClass().getSimpleName(), e.getMessage(), e);
		}

		synchronized (this) {
			status = STATUS_FINISHED;
		}
		Handler handler = this.getHandler();
		if (handler != null) {
			handler.sendEmptyMessage(STATUS_FINISHED);
		}
	}

	public int getStatus() {
		synchronized (this) {
			return this.status;
		}
	}

	public boolean hasError() {
		return this.error;
	}

	public Exception getException() {
		return this.exception;
	}

	public void setHandler(Handler handler) {
		this.handler = new SoftReference<Handler>(handler);
	}

	public Handler getHandler() {
		if (this.handler != null) {
			return this.handler.get();
		}
		return null;
	}

	@Override
	public long getId() {
		return this.url.hashCode();
	}
}